<template>
  <div class="app-container">
    <div ref="refsTable"  >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="登记时间">
          <el-date-picker
            v-model="dateRange"
            style="width:370px"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="录入时间">
          <el-date-picker
            v-model="entryRange"
            style="width:370px"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="项目类型" prop="projectTypeId">
          <el-autocomplete class="inline-input" v-model="queryParams.projectTypeName" :fetch-suggestions="querySearch"
            placeholder="请选择" @select="handleSelectProject" @focus="change(1)" style="width:221px"
            clearable></el-autocomplete>
          <!-- <el-select
            v-model="queryParams.projectTypeId"
            placeholder="全部"
            clearable
            style="width:221px"
          >
          <el-option value label="全部"></el-option>
            <el-option
              v-for="item in projectTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item label="样本类型" prop="sampleTypeId">
          <el-autocomplete class="inline-input" v-model="queryParams.sampleTypeName" :fetch-suggestions="querySearch"
            placeholder="请选择" @select="handleSelectSample" @focus="change(0)" style="width:221px"
            clearable></el-autocomplete>
          <!-- <el-select
            v-model="queryParams.sampleTypeId"
            placeholder="全部"
            clearable
            style="width:221px"
          >
          <el-option value label="全部"></el-option>
            <el-option
              v-for="item in sampleTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item label="专业组" prop="professionalGroupId">
          <el-select
            v-model="queryParams.professionalGroupId"
            placeholder="全部"
            clearable
            style="width:221px"
          >
          <el-option value label="全部"></el-option>
            <el-option
              v-for="item in professionalList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="条形码" prop="barcodeCode">
          <el-input
            v-model="queryParams.barcodeCode"
            placeholder="请输入条形码"
            clearable
            style="width:221px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="实验编号" prop="experimentNumber">
          <el-input
            v-model="queryParams.experimentNumber"
            placeholder="实验编号或流水号"
            clearable
            style="width:221px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="剩余时间">
          <el-form-item prop="symbol">
            <el-select v-model="queryParams.symbol" clearable style="width: 100px;">
              <el-option
                v-for="item in symbolList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="surplus">
            <el-input
              v-model="surplus"
              placeholder="请输入时间"
              clearable
              style="width: 118px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-select v-model="timeUnit" clearable style="width: 100px;">
              <el-option
                v-for="item in timeList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="1.5"></el-col>
        <el-col :span="1.5">
          <!--        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
          <el-dropdown trigger="click">
            <el-button type="primary" size="mini">
              导出
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleExport('now')">导出当前</el-dropdown-item>
              <el-dropdown-item @click.native="handleExport('all')">导出全部</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </div>

    <el-table
      :row-class-name="rowStyle"
      border
      highlight-current-row
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
      :height="heights"
      :header-cell-style="{
        background: '#ebebeb'
      }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <af-table-column label="条码号" align="center" prop="barcodeCode" />
      <af-table-column label="项目类型" align="center" width="350" prop="projectTypeName"></af-table-column>
      <af-table-column label="实验编号" align="center" prop="experimentNumber" />
      <af-table-column label="状态" align="center">
        <template slot-scope="scope">
          {{ scope.row.mainState === 6 ? analyzeSubStateName[scope.row.mainState] : mainStateName[scope.row.mainState]
          }}
        </template>
      </af-table-column>
      <af-table-column label="登记时间" align="center" prop="registrationTime" />
      <af-table-column label="录入时间" align="center" prop="registerCreateDate" />
      <af-table-column label="送检姓名" align="center" prop="submitName" />
      <af-table-column label="送检单位" align="center" prop="inspectionUnit" />
      <af-table-column label="平台类型" align="center" prop="platformTypeName" />
      <af-table-column label="样本类型" align="center" prop="sampleTypeName" />
      <af-table-column label="外包单位" align="center" prop="outName" />
      <af-table-column label="报告剩余时间" align="center">
        <template slot-scope="scope">
          {{
          scope.row.remainingTime >= 86400 ? Math.round(scope.row.remainingTime / 86400 * 10) / 10 + 'day' :
          scope.row.remainingTime < 86400 && scope.row.remainingTime >= 3600 ?
          Math.round(scope.row.remainingTime / 3600 * 10) / 10 + 'hour' : Math.round(scope.row.remainingTime / 60 *
          10) / 10 + 'min'
          }}
        </template>
      </af-table-column>
    </el-table>
    <div>
      <pagination
         
        style="margin:0;padding: 0;"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { getWarnList } from "@/api/auxiliary/assistManagement/warning";
import { professional } from "@/api/dictionary/systemDictionary/professional";
import { projectType } from "@/api/dictionary/systemDictionary/projectType";
import { sampleType } from "@/api/dictionary/systemDictionary/sampleType";
import { technology } from "@/api/dictionary/qualityControl/technology";

export default {
  name: "print",
  data() {
    return {
      pickerOptions: {
        disabledDate(time){
          return time.getTime()>Date.now()
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预警数据
      typeList: [],
      // 专业组数据
      professionalList: [],
      // 项目数据
      projectTypeList: [],
      // 样本数据
      sampleTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 登记日期范围
      dateRange: [],
      // 录入时间范围
      entryRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        barcodeCode: undefined,
        experimentNumber: undefined,
        remainingTime: undefined,
        professionalGroupId: '',
        sampleTypeId: '',
        projectTypeId: '',
        symbol: 1,
        startRegisterTime: undefined,
        endRegisterTime: undefined
      },
      mainStateName: {
        1: "已录入",
        2: "已登记",
        3: "已入库",
        4: "已提取",
        5: "已建库",
        6: "已测序",
        7: "已分析",
        8: "已初审",
        9: "已确认初审",
        10: "已复审",
        11: "已提交",
        12: "已上传",
        13: "不上传"
      },
      analyzeSubStateName: {
        0: "待分析",
        1: "分析中",
        2: "分析失败",
        3: "分析成功"
      },
      platformTypeList: [
        {
          title: "微生物",
          id: 1
        },
        {
          title: "肿瘤",
          id: 2
        },
        {
          title: "科研",
          id: 3
        }
      ],
      symbolList: [
        {
          title: ">=",
          id: 1
        },
        {
          title: "<=",
          id: 0
        }
      ],
      timeList: [
        {
          title: "min",
          id: 1
        },
        {
          title: "h",
          id: 2
        },
        {
          title: "day",
          id: 3
        }
      ],
      surplus: 30,
      timeUnit: 1,
      heights: undefined,
      
    };
  },
  created() {
    this.dateRange[0] = this.parseTime(
      new Date(new Date().toLocaleDateString()).getTime() 
    );
    this.dateRange[1] = this.parseTime(
      new Date(new Date().toLocaleDateString()).getTime() - 1000+ 24 * 60 * 60 * 1000
    );
    this.entryRange[0] = this.parseTime(
      new Date(new Date().toLocaleDateString()).getTime()
    );
    this.entryRange[1] = this.parseTime(
      new Date(new Date().toLocaleDateString()).getTime() - 1000+ 24 * 60 * 60 * 1000
    );
    this.getList();
    this.otherList();
  },
  mounted() {
    this.$nextTick(() => {
      // 根据浏览器高度设置初始高度
      this.heights =
        window.innerHeight - this.$refs.refsTable.offsetHeight - 160;
      // 监听浏览器高度变化，修改表格高度
      window.onresize = () => {
        this.heights =
          window.innerHeight - this.$refs.refsTable.offsetHeight - 160;
      };
    });
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    // 多个下拉框的数据
    loadAll() {
      const array = [
        this.sampleTypeList,
        this.projectTypeList,
      ];
      return array;
    },
    // 聚焦下拉框时
    change(i) {
      this.restaurants = this.loadAll()[i];
    },
    handleSelectSample(item) {
      this.queryParams.sampleType = item.id
    },
    handleSelectProject(item) {
      this.queryParams.projectType = item.id
    },
    /** 预警 */
    getList() {
      this.loading = true;
      getWarnList(
        this.addentryDateRange(
          this.queryParams,
          this.dateRange,
          this.entryRange
        )
      ).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    otherList() {
      professional().then(response => {
        this.professionalList = response.rows;
      });
      projectType().then(res => {
        res.rows.map((el) => {
        this.projectTypeList.push({
          value: el.name,
          id: el.id
        })
      })
      });
      sampleType().then(res => {
        res.rows.map(el => {
        this.sampleTypeList.push({
          value: el.name,
          id: el.id
        })
      })
      });
    },
    // 表单重置
    reset() {
      this.form = {
        pageNum: 1,
        pageSize: 20,
        barcodeCode: undefined,
        experimentNumber: undefined,
        remainingTime: undefined,
        professionalGroupId: undefined,
        sampleTypeId: undefined,
        projectTypeId: undefined
      };
      this.resetForm("form");
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          if (this.timeUnit === 1) {
            this.queryParams.remainingTime = this.surplus * 60;
          } else if (this.timeUnit === 2) {
            this.queryParams.remainingTime = this.surplus * 3600;
          } else if (this.timeUnit === 3) {
            this.queryParams.remainingTime = this.surplus * 86400;
          }
          this.queryParams.pageNum = 1;
          this.getList();
        }
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.entryRange = [];
      this.surplus = undefined;
      this.timeUnit = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // /** 导出按钮操作 */
    handleExport(e) {
      var different = "";
      var params = "";
      if (e === "now") {
        different = "当前";
        params = this.queryParams; //对应接口参数
      } else if (e === "all") {
        different = "所有";
        params = null;
      } else {
        return;
      }
      let that = this;
      let loading;
      this.$confirm("是否确认导出" + different + "数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          loading = that.$loading({
            lock: true,
            text: "导出中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
          });
          getWarnList(
            that.addentryDateRange(params, that.dateRange, that.entryRange)
          ).then(response => {
            let mydata = [
              [
                "序号",
                "条码号",
                "项目类型",
                "实验编号",
                "状态",
                "登记时间",
                "录入时间",
                "送检姓名",
                "送检单位",
                "平台类型",
                "样本类型",
                "外包单位",
                "报告剩余时间"
              ],
              ...response.rows.map((item, index) => [
                index + 1,
                item.barcodeCode,
                item.projectTypeName,
                item.experimentNumber,
                item.mainState === 6
                  ? that.analyzeSubStateName[item.mainState]
                  : that.mainStateName[item.mainState],
                item.registrationTime,
                item.registerCreateDate,
                item.submitName,
                item.inspectionUnit,
                item.platformTypeName,
                item.sampleTypeName,
                item.outName,
                item.remainingTime >= 86400
                  ? Math.round((item.remainingTime / 86400) * 10) / 10 + "day"
                  : item.remainingTime < 86400 && item.remainingTime >= 3600
                  ? Math.round((item.remainingTime / 3600) * 10) / 10 + "hour"
                  : Math.round((item.remainingTime / 60) * 10) / 10 + "min"
              ])
            ];
            let requireMerge = [];
            that.$util.createxlsx({
              mydata,
              fileName: "预警监控",
              dataList: response.rows,
              type: "orderId",
              requireMerge,
              loading
            });
          });
        })
        .catch(function() {});
    },
    rowStyle({ row }) {
      var arr = this.ids;
      for (let i = 0; i < arr.length; i++) {
        if (row.id === arr[i]) {
          return "rowStyle";
        }
      }
    }
  }
};
</script>
<style scoped lang="scss">
.el-form-item {
  margin-bottom: 10px !important;
}

.app-container {
  height: 85vh;
}

::v-deep .el-table__body tr.current-row > td {
  background: #a8d6fe !important;
}

::v-deep .rowStyle {
  background-color: #a8d6fe !important;
}

::v-deep .el-table__body tr:hover > td {
  background: #a8d6fe !important;
}
.topDiv {
  ::v-deep .el-form-item__label {
    font-size: 12px;
    padding: 0 5px 0 0;
    margin: 0;
  }
}
</style>
